package Day20;

public class Demo01 {
    //生产者与消费者
    public static void main(String[] args) {
        Food f = new Food();
//        Waiter w = new Waiter(f);
//        Cook c = new Cook(f);
//        new Thread(w).start();
//        new Thread(c).start();
        new Cook(f).start();
        new Waiter(f).start();
    }
    static class Waiter extends Thread{
        private Food f;
        public Waiter(Food f) {
            this.f = f;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    f.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    static class Cook extends Thread{
        private Food f;
        public Cook(Food f) {
            this.f = f;
        }
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                if(i%2 == 0){
                    try {
                        f.setNameAndTaste("老干妈","香辣味");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    try {
                        f.setNameAndTaste("香蕉","甜的");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    static class Food{
        private String name;
        private String taste;
        private boolean flag = true;
        public synchronized void setNameAndTaste(String name,String taste) throws InterruptedException {
            if (flag == true) {
                this.name = name;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.taste = taste;
            }
            flag = false;
            this.notifyAll();
            this.wait();
        }
        public synchronized void get() throws InterruptedException {
            if (flag == false) {
                System.out.println("服务员上菜，菜名：" + name + "  味道：" + taste);
                flag = true;
                this.notifyAll();
                this.wait();
            }
        }


    }
}
